package com.ykq.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author: 闫克起
 * @Description:
 * @Date: Create in 10:41 2024/10/21
 */
@WebFilter(urlPatterns = "/*")
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void destroy() {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
         HttpServletRequest request= (HttpServletRequest) servletRequest;
        HttpServletResponse response= (HttpServletResponse) servletResponse;
        //1.获取请求路径
        String uri = request.getRequestURI();
        System.out.println(uri+"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
        //2.判断是否是为放行资源路径，如果是，放行
        if("/login.jsp".equals(uri)||
           "/staff/login".equals(uri)||
           uri.endsWith(".jpg")||
           uri.endsWith(".jpeg")||
           uri.endsWith(".png")||
           uri.endsWith(".css")||
           uri.endsWith(".js")
         ){
            filterChain.doFilter(request,response);
        }else{
            //3.判断是否登录，如果登录，放行，否则跳转到登录页面
            Object staff = request.getSession().getAttribute("staff");
            if(staff!=null){
                filterChain.doFilter(request,response);
            }else{
                response.sendRedirect("/login.jsp");
            }
        }
    }
}
